import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

//使用不同类型的子项创建列表
/*
步骤
1、使用不同类型的数据创建数据源
2、将数据源转换为Widgets列表
 */
class ListViewEx extends StatelessWidget{
  final List<ListItem> items = List<ListItem>.generate(1000, (int index){
    if(index % 6 == 0){
      return HeadingItem('Heading $index');
    }else{
      return MessageItem('Sender $index', 'Message body $index');
    }
  });
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('不同类型的列表'),),
      body: ListView.builder(itemBuilder: (BuildContext context, int index){
        final item = items[index];
        if(item is HeadingItem){
          return ListTile(title: Text(item.heading,style: Theme.of(context).textTheme.headline,),);
        }else if(item is MessageItem){
          return ListTile(title: Text(item.sender),subtitle: Text(item.body),);
        }
        return ListTile(title: Text('error data!!!'),);
      },
      itemCount: items.length,),
    );
  }
}

//the base class for the different types of items the list can contain
abstract class ListItem{}

//A ListItem that contains data to display a heading
class HeadingItem implements ListItem{
  final String heading;
  HeadingItem(this.heading);
}

//A ListItem that contains data to display a message
class MessageItem implements ListItem{
  final String sender;
  final String body;
  MessageItem(this.sender, this.body);
}

